<template>
  <div>
    <el-upload
      :action="ossUploadUrl"
      :data="dataObj"
      :accept="accepts"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
    >
      <div slot="file" slot-scope="{ file }">
        <!-- 图片显示 -->
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />

        <span class="el-upload-list__item-actions">
          <!-- 预览按钮 -->
          <span
            class="el-upload-list__item-preview"
            @click="handlePreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <!-- 删除按钮 -->
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>

      <!-- 触发文件选择框的内容 -->
      <i slot="trigger" class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">
        只能上传{{ accepts }}文件，且不超过{{ fileMaxSize }}MB
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" alt="" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import { policy, deleteFile } from "@/api/oss";
export default {
  props: {
    value: String,
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        // callback: '',
      },
      ossUploadUrl: "http://atvris.oss-cn-beijing.aliyuncs.com",
      dialogImageUrl: null,
      dialogVisible: false,
      accepts: ".jpeg, .jpg, .png",
      fileMaxSize: 4,
    };
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== "") {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [
        {
          name: this.imageName,
          url: this.imageUrl,
        },
      ];
    },
    showFileList: {
      get: function () {
        return (
          this.value !== null && this.value !== "" && this.value !== undefined
        );
      },
      set: function (newValue) {},
    },
  },
  methods: {
    emitInput(val) {
      this.$emit("input", val);
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true;
      this.fileList.pop();
      let url = this.dataObj.host + "/" + this.dataObj.dir + "/" + file.name;
      this.fileList.push({ name: file.name, url: url });
      this.emitInput(this.fileList[0].url);
    },
    handleExceed(files, fileList) {
      this.$message.warning("当前限制选择1张图片");
    },
    handlePreview(file) {
      // 点击了预览按钮
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      deleteFile(file.url).then(res => {
        this.emitInput("");
      });
    },
    beforeUpload(file) {
      const isValidType =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      // 限制上传的大小
      const isLt4M = file.size / 1024 / 1024 < 4;

      if (!isValidType) {
        this.$message.error("上传图片只能是" + this.accepts + "格式!");
        return false;
      }

      if (!isLt4M) {
        this.$message.error("上传图片大小不能超过" + this.fileMaxSize + "MB!");
        return false;
      }
      let _self = this;
      return new Promise((resolve, reject) => {
        policy()
          .then((res) => {
            _self.dataObj.policy = res.data.policy;
            _self.dataObj.signature = res.data.signature;
            _self.dataObj.ossaccessKeyId = res.data.accessKeyId;
            _self.dataObj.key = res.data.dir + "/${filename}";
            _self.dataObj.dir = res.data.dir;
            _self.dataObj.host = res.data.host;
            // _self.dataObj.callback = res.data.callback;
            resolve(true);
          })
          .catch((err) => {
            console.log(err);
            reject(false);
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.cover-upload-show-tip {
  position: absolute;
  right: 0;
  bottom: 0;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-justify-content: space-around;
  -ms-flex-pack: distribute;
  justify-content: space-around;
  font-size: 12px;
  color: #fff;
  text-align: center;
  line-height: 26px;
  width: 100%;
  border-radius: 4px 0 4px 0;
  z-index: 100;
}
.cover-upload-show-tip-upload {
  width: 50%;
  background: rgba(0, 0, 0, 0.5);
  margin-right: 2px;
}
.cover-upload-show-tip-edit {
  width: 50%;
  background: rgba(0, 0, 0, 0.5);
  margin-left: 2px;
}
</style>